package org.example;

import java.util.ArrayDeque;
import java.util.Deque;

public class Test5 {
    //leetcode 111 二叉树的最小深度 https://leetcode.cn/problems/minimum-depth-of-binary-tree/
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) return 1;
        int leftDeepth = (int)1e5;
        int rightDeepth = (int)1e5;
        if (root.left != null) {
            leftDeepth = minDepth(root.left);
        }
        if (root.right != null) {
            rightDeepth = minDepth(root.right);
        }
        return Math.min(leftDeepth,rightDeepth) + 1;
    }

    public int minDepth2(TreeNode root) {
        if (root == null) return 0;
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);
        int deepth = 0;
        while (!deque.isEmpty()) {
            int count = deque.size();
            deepth++;
            while (count > 0) {
                TreeNode tmp = deque.poll();
                if (tmp.left == null && tmp.right == null) return deepth;
                if (tmp.left != null) deque.add(tmp.left);
                if (tmp.right != null) deque.add(tmp.right);
                count--;
            }
        }
        return deepth;
    }
}
